package com.tajiang.business.order.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tajiang.business.R;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.widget.dialog.CallDialog;
import com.tajiang.business.model.Order;
import com.tajiang.business.model.OrderGoods;
import com.tajiang.business.model.OrderPrinted;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by ciko on 16/6/12.
 */
public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.MyViewHolder> {

    public static final int ORDER_TYPE_NORMAL = 0;
    public static final int ORDER_TYPE_SEARCH = 1;
    public static final int ORDER_TYPE_HISTORY = 2;

    private int orderType = ORDER_TYPE_NORMAL;

    private Context context;
    private List<Order> dataList;
    private SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);
    private OnPrintSingleOrderListener onPrintSingleOrderListener;
    private NumberFormat numberFormat = NumberFormat.getInstance();

    /**
     * 检查是否清空了订单列表
     *
     * @param onPrintSingleOrderListener
     */
    public void setOnPrintSingleOrderListener(OnPrintSingleOrderListener onPrintSingleOrderListener) {
        this.onPrintSingleOrderListener = onPrintSingleOrderListener;
    }

    public interface OnPrintSingleOrderListener {
        public void OnPrintSingleOrder(List<Order> dataList, int position);
    }

    public OrderListAdapter(Context context, List<Order> dataList, int orderType) {
        this.context = context;
        this.dataList = dataList;
        this.orderType = orderType;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_order, null);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        final Order order = dataList.get(position);
        Calendar calendar = Calendar.getInstance();
//        calendar.setTimeInMillis(order.getPaymentTime());
//        if (orderType == ORDER_TYPE_NORMAL&& ! DateUtils.getCurrentDayMonthYearByMills(esTime).equals(DateUtils.getCurrentDayMonthYear())) {   //预订单
//        if (orderType == ORDER_TYPE_NORMAL && order.getEstimatedTimev2().contains("明天")) {   //预订单
//            holder.ivFlag.setImageResource(R.mipmap.icon_flag_pre_order);
//        } else {
//            holder.ivFlag.setImageResource(R.mipmap.icon_flag_order);
//        }
//        holder.tvDeliverExplain.setText(order.getDeliverExplain());
//        holder.tvEstimatedTime.setText(order.getEstimatedTimev2());
//        holder.tvOrderTime.setText(format.format(calendar.getTime()) + "下单");
//        holder.tvApartment.setText(order.getOrderAddress());
//        holder.tvName.setText(order.getTrueName());
////        holder.tvPhone.setText(order.getBuyerPhone());
//        holder.phone = order.getBuyerPhone();
//        holder.tvOrder.setText("订单号:" + order.getOrderSn());
//        holder.llGoodsList.removeAllViews();
//
//        if (order.getOrderGoodsList() != null) {
//            for (OrderGoods goods : order.getOrderGoodsList()) {
//                LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(holder.getContext()).inflate(R.layout.item_order_goods, holder.llGoodsList, false);
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//                linearLayout.setLayoutParams(params);
//                TextView tvGoodsName = ButterKnife.findById(linearLayout, R.id.tv_goods_name);
//                TextView tvGoodsNum = ButterKnife.findById(linearLayout, R.id.tv_goods_num);
//                TextView tvGoodsPrice = ButterKnife.findById(linearLayout, R.id.tv_goods_price);
//                tvGoodsName.setText(goods.getGoodsName());
//                tvGoodsNum.setText("x " + numberFormat.format(goods.getGoodsNum()));
//                tvGoodsPrice.setText("￥" + numberFormat.format(goods.getGoodsNum() * goods.getShowPrice()));
//                holder.llGoodsList.addView(linearLayout);
//            }
//        }
//        //商家活动优惠折扣
//        if (order.getDiscount() != null && order.getDiscount().compareTo(new BigDecimal(BigInteger.ZERO)) > 0) {
//            holder.rlBusinessDiscount.setVisibility(View.VISIBLE);
//            holder.tvBusinessDiscount.setText("-￥" + numberFormat.format(order.getDiscount()));
//        } else {
//            holder.rlBusinessDiscount.setVisibility(View.GONE);
//        }
//        //订单菜品合计总价
//        holder.tvOrderPrice.setText("￥" + numberFormat.format(order.getShowOrderAmount() != null ?
//                order.getShowOrderAmount().doubleValue() : new Double(0)));
//
//        if (order.getOrderGoodsList() != null && order.getOrderGoodsList().get(0).getOrderPrint() == Order.ORDER_PRINTED) {
//            holder.tvOrderStatue.setText("已打印");
////            holder.tvOrderStatue.setTextColor(context.getResources().getColor(R.color.text_black_1));
//            holder.tvOrderStatue.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    String rel = BTPrintUtils.getInstance().printSinglePage(context, order, OrderPrinted.PRINT_TYPE_MANUAL);
//                    return true;
//                }
//            });
//            holder.btnToPrint.setVisibility(View.GONE);
//        } else {
//            holder.tvOrderStatue.setText("未打印");
//            if (orderType == ORDER_TYPE_NORMAL) {  //确认打印
//                holder.btnToPrint.setVisibility(View.VISIBLE);
//            } else {   //历史订单
//                holder.btnToPrint.setVisibility(View.GONE);
//            }
//        }

    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public int removeItem(int position) {
        this.dataList.remove(position);
        notifyItemRemoved(position);//Attention!
        return this.dataList.size();
    }

    public List<Order> getData() {
        return dataList;
    }

    public void updateDataSetChanged(List<Order> dataList) {
        this.dataList.clear();
        this.dataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public void AddAllAndUpdateData(List<Order> newDataList) {
        this.dataList.addAll(newDataList);
        notifyDataSetChanged();
    }


    class MyViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_flag)
        ImageView ivFlag;
        @BindView(R.id.tv_estimated_time)
        TextView tvEstimatedTime;
        @BindView(R.id.tv_order_time)
        TextView tvOrderTime;
        @BindView(R.id.tv_order_statue)
        TextView tvOrderStatue;
        @BindView(R.id.tv_apartment)
        TextView tvApartment;
        @BindView(R.id.tv_name)
        TextView tvName;
        //@BindView(R.id.tv_phone)
        //TextView tvPhone;
        @BindView(R.id.tv_back_up)
        TextView tvBackUp;
        @BindView(R.id.tv_deliver_explain)
        TextView tvDeliverExplain;
        @BindView(R.id.ll_goods_list)
        LinearLayout llGoodsList;
        @BindView(R.id.tv_order_price)
        TextView tvOrderPrice;
        @BindView(R.id.tv_order)
        TextView tvOrder;
        @BindView(R.id.iv_dialog_phone)
        ImageView ivDialogPhone;
        @BindView(R.id.tv_business_discount)
        TextView tvBusinessDiscount;
        @BindView(R.id.rl_business_discount)
        RelativeLayout rlBusinessDiscount;
        @BindView(R.id.btn_to_print)
        Button btnToPrint;

        private String phone;

        private Timer timer_one = null;
        private int timer_cnt = 0;

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            initLister();
        }

        private void initLister() {
            /**
             * 订单打印
             */

            //  RxView.clicks(tvToPrint).debounce(500, TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            //      @Override
            //      public void call(Void aVoid) {
            //             onPrintSingleOrderListener.OnPrintSingleOrder(dataList, getLayoutPosition());
            //      }
            // });

            btnToPrint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        LogUtils.e("【519】btnToPrint.timer_cnt=" + timer_cnt);
                        if (timer_cnt > 0) {
                            return;
                        }

                        timer_cnt++;
                        timer_one = new Timer();
                        // 调度一个task，经过delay(ms)后开始进行调度，仅仅调度一次即可.
                        timer_one.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                timer_cnt = 0;
                            }
                        }, 1500);
                    } catch (Exception ex) {
                        LogUtils.e("【519】btnToPrint.ex=" + ex.getMessage());
                        return;
                    }

                    if (onPrintSingleOrderListener != null) {
                        onPrintSingleOrderListener.OnPrintSingleOrder(dataList, getLayoutPosition());
                    }
                }
            });

            /**
             * 拨打下单用户电话
             */
            ivDialogPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new CallDialog(getContext(), phone).show();
                }
            });
        }

        public Context getContext() {
            return itemView.getContext();
        }

    }

}
